#!/usr/bin/perl
#mailadmin-lib.pl

do "../web-lib.pl";
&init_config();
%access = get_module_acl();


#set_local_domain($localdomain)
#add hostname.localdomain to /var/qmail/locals and me defaultdomain qlusdomain
sub set_local_domain()
{
    my (@file, $i, $hostname, $localdomain, $out);

    $hostname = `hostname`;
    chomp($hostname);

    $localdomain = @_[0];
    $localdomain = "localdomain" unless ($localdomain);

    #echo to /var/qmail/control/me file
    $str = $hostname . '@' . $localdomain;
    $out = `echo $str > $config{'me_f'} `;

    #echo to /var/qmail/control/locals file
    $str = $hostname . '@' . $localdomain;
    $out = `echo $str > $config{'locals_f'} `;
    
    #echo to /var/qmail/control/defaultdomain file
    $out = `echo $localdomain > $config{'defaultdomain'} `;

    #echo to /var/qmail/control/plus_domain file
    $out = `echo $plus_domain > $config{'plus_domain'} `;
    
}


#get_vdomain_list(\%vdlist)
sub get_vdomain_list()
{
    my ($ptr_vdl, @file, $i, @line, $unum);

    $ptr_vdl = @_[0];

    open (VDOMAIN, $config{'virtualdomains_f'});
    @file = <VDOMAIN>;
    close (VDOMAIN);

    for ($i = 0; $i < @file; $i++)
    {
	chomp($file[$i]);

	@line = split (/:/, $file[$i]);
	if($line[0])
	{
	    $unum = `$config{'vdominfo'} -t $line[0]`;
	    chomp($unum);
	    $ptr_vdl->{$line[0]} = $unum;
	}
    }
}

#get_service_status(\%status)
#get mailserv, pop3, smtp, mailserv status
sub get_service_status()
{
    my ($ptr_st, @out, $i);

    $ptr_st = @_[0];

    #mailserv status
    @out = `ps -A | grep qmail-send 2>/dev/null`;

    if (($out[0] =~ /qmail-send/) && ($out[0] !~ /\s+grep\s+/)) {
	$ptr_st->{'mailserv'} = $text{'st_run'};
    } else {
	$ptr_st->{'mailserv'} = $text{'st_stop'};
    }

    #smtp status
    @out = `ps -auwx | grep master 2>/dev/null`;
    if (($out[0] =~ /postfix/) && ($out[0] !~ /\s+grep\s+/)) {
	$ptr_st->{'smtpserv'} = $text{'st_run'};
    } else {
	$ptr_st->{'smtpserv'} = $text{'st_stop'};
    }

    #pop3 status
    @out = `ps -auwx | grep dovecot 2>/dev/null`;
    if (($out[0] =~ /dovecot/) && ($out[0] !~ /\s+grep\s+/)) {
	$ptr_st->{'popserv'} = $text{'st_run'};
    } else {
	$ptr_st->{'popserv'} = $text{'st_stop'};
    }

    #webmail server status
    @out = `ps -auwx | grep webmail-httpd.conf | grep root 2>/dev/null`;
    if (($out[0] =~ /webmail-httpd\.conf/) && ($out[0] !~ /\s+grep\s+/)) {
	$ptr_st->{'webmailserv'} = $text{'st_run'};
    } else {
	$ptr_st->{'webmailserv'} = $text{'st_stop'};
    }    
}

#serv_act($servname, $action)
sub serv_act()
{
    my ($name, $action, $out, @line, my $child_pid);
    my (@psout);

    $name = @_[0];
    $action = @_[1];

    if ($name eq 'mailserv') {
	goto START_MAILSERV if ($action eq 'start');
	goto STOP_MAILSERV;
    }

    if ($name eq 'smtpserv') {
	goto START_SMTP if ($action eq 'start');
	goto STOP_SMTP;
    }

    if ($name eq 'popserv') {
	goto START_POP3 if ($action eq 'start');
	goto STOP_POP3;
    }

    if ($name eq 'webmailserv') {
	goto START_WEBMAIL if ($action eq 'start');
	goto STOP_WEBMAIL;
    }
    return;

  STOP_MAILSERV:
    $out = `killall qmail-remote`;
    @psout = `ps -auwx | grep qmail-send`;
    for ($i = 0; $i < @psout; $i++)
    {
	if (($psout[$i] =~ /qmail-send/) && ($psout[$i] !~ /\s*ps\s*|\s*grep\s*/))
	{
	    @line = split (/\s+/, $psout[$i]);
	    $out = `kill -9 $line[1] `;
	}
    }

    return if ($action eq 'stop');
    sleep (1);
  START_MAILSERV:
    $child_pid=fork;
    if($child_pid) {
    }else{
	exec $config{'qmailstart'};	
    }
    return;

  STOP_SMTP:
    $out = `ps -auwx | grep master 2>/dev/null`;
    if ($out =~ /postfix/) {
	#@line = split (/\s+/, $out);
	#$out = `kill -9 $line[1] `;
	$out = `postfix stop`;
    }
    return if ($action eq 'stop');

    sleep (1);
  START_SMTP:
    #$child_pid=fork;
    #if($child_pid) {
    #}else{
#	exec $config{'smtpstart'};
#    }
    `postfix start`;
    return;

  STOP_POP3:
    $out = `ps -A | grep dovecot 2>/dev/null`;
    if ($out =~ /dovecot/) {
	#@line = split (/\s+/, $out);
	#$out = `kill $line[1] `;
	$out = `/etc/init.d/dovecot stop`;
    }
    return if ($action eq 'stop');
    sleep (1);

  START_POP3:
    #$child_pid=fork;
    #if($child_pid) {
    #}else{
    #	exec $config{'pop3start'};	
    #}
    `/etc/init.d/dovecot start`;
    return;

  STOP_WEBMAIL:
    $out = `ps -auwx | grep webmail-httpd.conf | grep root 2>/dev/null`;
    if ($out =~ /webmail-httpd\.conf/) {
	@line = split (/\s+/, $out);
	$out = `kill $line[1] `;
    }
    return if ($action eq 'stop');
    sleep (1);

  START_WEBMAIL:

    $out = `sh $config{'webmailstart'}`;
    return;
}

#bytes2M($nbytes)
sub bytes2M()
{
    my ($nbytes, $rt_m);

    $nbytes = @_[0];
    $nbytes =~ s/\D//g;
    $rt_m = $nbytes/1048756;
    return $rt_m;
}

#check_input_num($input_num)
sub check_input_num()
{
    my ($input_num, $error_msg,$bignum, $smallnum, $str_length);

    $input_num = @_[0];

    if($input_num =~ /^(\d+)(.*)/)
    {
	$bignum = $1;		
	if($2)
	{
	    $smallnum = $2;
	    if($smallnum =~ /^\.(\d+)$/)
	    {
		$error_msg = "";
		$str_length = length($bignum);

		if($str_length > 6)
		{
		    $error_msg = $text{'msg_err_input_num_tobig'};
		}
	    }
	    else
	    {
		$error_msg = $text{"msg_err_input_not_num"};
	    }
	}
	else
	{
	    $error_msg = "";
	    $str_length = length($input_num);

	    if($str_length > 6)
	    {
		$error_msg = $text{'msg_err_input_num_tobig'};
	    }
	}
    }
    else
    {
	$error_msg = $text{"msg_err_input_not_num"};
    }
    return $error_msg;
}

#check_input_not_integer(inputnum)
sub check_input_not_integer()
{
	my ($input_num, $error_msg,$bignum, $smallnum, $str_length);

	$input_num = @_[0];

	if($input_num =~ /^(\d+)$/)
	{
		$bignum = $1;
		$error_msg = "";
		$str_length = length($input_num);
		if($str_length > $config{'max_int_length'})
		{
			$error_msg = $text{'msg_err_input_not_integer'};
		}
	}
	else
	{
		$error_msg = $text{"msg_err_input_not_integer"};
	}
	return $error_msg;
}

#get_dftuinfo(\%dftuinfo)
sub get_dftuinfo()
{
    my ($ptr_dftinfo, @file, $i);

    $ptr_dftinfo = @_[0];

    open (DFTUSRCONF, $config{'dft_uconf'});
    @file = <DFTUSRCONF>;
    close (DFTUSRCONF);

    for ($i = 0; $i < @file; $i++)
    {
	chomp ($file[$i]);

	$file[$i] =~ s/#.*$//;

	if ($file[$i] =~ /PASSWORD=(.*)/)
	{
	    $ptr_dftinfo->{'upasswd'} = $1;
	}

	if ($file[$i] =~ /MBX_QUOTA=(.*)/)
	{
	    $ptr_dftinfo->{'uquota'} = $1;
	}
    }
}

#save_dftuinfo(\%dftuinfo)
sub save_dftuinfo()
{
    my ($ptr_dftinfo, @file, $i, $k);

    $ptr_dftinfo = @_[0];

    open (DFTUSRCONF, "$config{'dft_uconf'}");
    @file = <DFTUSRCONF>;
    close (DFTUSRCONF);

    for ($i = @file - 1; $i >= 0; $i--)
    {
	chomp ($file[$i]);

	$file[$i] =~ s/#.*$//;

	if ($file[$i] =~ /PASSWORD=(.*)/)
	{
	    splice @file, $i, 1;
	    next;
	}

	if ($file[$i] =~ /MBX_QUOTA=(.*)/)
	{
	    splice @file, $i, 1;
	    next;
	}
    }

    foreach $k (keys %$ptr_dftinfo)
    {
	if ($k eq 'upasswd') {
	    push @file, "PASSWORD=" . $ptr_dftinfo->{'upasswd'} . "\n";
	    next;
	} elsif ($k eq 'uquota') {
	    push @file, "MBX_QUOTA=" . $ptr_dftinfo->{'uquota'} . "\n";
	    next;
	}
    }

    open (DFTUSRCONF, "> $config{'dft_uconf'}");
    print DFTUSRCONF @file;
    close (DFTUSRCONF);
}

#save_databytes($databytes)
sub save_databytes()
{
    my ($databytes);

    $databytes = @_[0];

    open (DATABYTES, "> $config{'databytes_f'}");
    print DATABYTES $databytes."\n";
    close(DATABYTES);
}

#get_msrvconf(\%msrvconf)
sub get_msrvconf()
{
    my ($ptr, @file, $i);

    $ptr = @_[0];

    $ptr->{'databytes'} = $config{'dft_databytes'};

    @file = &ez_system12('cat', $config{'databytes_f'});
    for ($i = 0;  $i < @file; $i++)
    {
	chomp($file[$i]);
	$file[$i] =~ s/#.*$//;
	if ($file[$i] =~ /(\d+)/)
	{
	    $ptr->{'databytes'} = $1;
	    last;
	}
    }
}

#get_vuser_info($uname, $dname, \%uinfo)
sub get_vuser_info()
{
    my ($uname, $dname, $ptr_uinfo, @out, $i, @file);

    $uname = @_[0];
    $dname = @_[1];
    $ptr_uinfo = @_[2];    

    $out = &ez_system('rm', '-f', $config{'flink_domains'} . '/' . $dname . '/' . $uname . '/' . 'Maildir/maildirsize');
    $out = &ez_system12($config{'vuserinfo'}, $uname . '@' . $dname);
    
    @file = split ('\n', $out);

    for ($i = 0; $i < @file; $i++)
    {
	chomp($file[$i]);

	if ($file[$i] =~ /^clear passwd:/) {

	    $ptr_uinfo->{'clear passwd'} = $file[$i];
	    $ptr_uinfo->{'clear passwd'} =~ s/^clear passwd:\s+//;	    
	    next;
	}

	if ($file[$i] =~ /^dir:/) {
	    $ptr_uinfo->{'dir'} = $file[$i];
	    $ptr_uinfo->{'dir'} =~ s/^dir:\s+//;	    
	    next;
	}

	if ($file[$i] =~ /^quota:/) {
	    $ptr_uinfo->{'quota'} = $file[$i];
	    $ptr_uinfo->{'quota'} =~ s/^quota:\s+//;	    
	    next;
	}

	if ($file[$i] =~ /^usage:/) {
	    $ptr_uinfo->{'usage'} = $file[$i];
	    $ptr_uinfo->{'usage'} =~ s/^usage:\s+//;	    
	    next;
	}
    }
}

#sub check_simbol_uname($inputname)
#return $error_msg
sub check_simbol_name()
{
	my ($inputname, $error_msg);

	$inputname = @_[0];
	$error_msg = "";

	if(($inputname =~ /[^a-zA-Z0-9]/) || ($inputname =~ /^\d+(.*)/) || (length($inputname) < 3))
	{
		$error_msg = &text('msg_err_isnt_simbol_uname', $inputname);
	}

	return $error_msg;
}


#create_user(\@ulist, $dname, $password, $uquota)
#return $err_msg
sub create_user()
{
    my ($pt_ul, $dname, $password, $uquota);
    my ($out, $cmd, $err_msg);

    $pt_ul = @_[0];
    $dname = @_[1];
    $password = @_[2];
    $uquota = sprintf "%.0f", @_[3]*1048756;
    $err_msg = "";

    for ($i = 0; ($i < @$pt_ul) && ($i < $config{'bataction_num'}); $i++)
    {
	$out = &check_simbol_name($pt_ul->[$i]);
	if ($out)
	{
	    $err_msg = $err_msg . $out . "<p>";
	    next;
	}
	$out = &ez_system12 ($config{'vadduser'}, $pt_ul->[$i].'@'.$dname, $password, "-q", $uquota);

	if ($out =~ /error/i)
	{
	    $err_msg = $err_msg . &text('msg_err_adduser', $pt_ul->[$i].'@'.$dname);
	    next;
	}
    }

    return $err_msg;
}

#modify_user(\@ulist, $dname, $password, $uquota)
sub modify_user()
{
    my ($pt_ul, $dname, $password, $uquota);
    my ($out, $cmd, $err_msg);

    $pt_ul = @_[0];
    $dname = @_[1];
    $password = @_[2];
    $uquota = sprintf "%.0f", @_[3]*1048756;
    $err_msg = "";

    for ($i = 0; ($i < @$pt_ul) && ($i < $config{'bataction_num'}); $i++)
    {
	$out = &check_simbol_name($pt_ul->[$i]);
	if ($out)
	{
	    $err_msg = $err_msg . $out . "<p>";
	    next;
	}

	$out = &ez_system12 ($config{'vmoduser'}, $pt_ul->[$i].'@'.$dname, $password, "-C", $password, "-q", $uquota);

	if ($out =~ /no such user/i)
	{
	    $err_msg = $err_msg . &text('msg_err_moduser', $pt_ul->[$i].'@'.$dname);
	    next;
	}
    }

    return $err_msg;
}

#delete_user(\@ulist, $dname)
sub delete_user(\@ulist, $dname)
{
    my ($pt_ul, $dname);
    my ($out, $cmd, $err_msg);

    $pt_ul = @_[0];
    $dname = @_[1];

    $err_msg = "";

    for ($i = 0; ($i < @$pt_ul) && ($i < $config{'bataction_num'}); $i++)
    {
	$out = &ez_system12 ($config{'vdeluser'},  $pt_ul->[$i].'@'.$dname);

	if ($out =~ /error/i)
	{
	    $err_msg = $err_msg . &text('msg_err_deluser', $pt_ul->[$i].'@'.$dname);
	    next;
	}
    }

    return $err_msg;
}

#create_domain($dname, $password)
sub create_domain()
{
    my ($dname, $password);
    my ($out, $cmd, $err_msg);
    my (@file, $i , @line);

    $dname = @_[0];
    $password = @_[1];
    $err_msg = "";

#    $out = &check_simbol_name($dname);
#    if ($out)
#    {
#	$err_msg = $out;
#	return $err_msg;
#    }

    $out = &ez_system12 ($config{'vadddomain'}, $dname, $password);

    if ($out =~ /error/i)
    {
	$err_msg = &text('msg_err_adddomain', $dname);
    }
    else
    {
	open (DOMAINBAK , $config{'domains_cur'} );
	@file = <DOMAINBAK>;
	close (DOMAINBAK);

	for ($i = @file - 1; $i >= 0; $i--)
	{
	    @line = split (':', $file[$i]);
	    if ($line[0] eq $dname)
	    {
		splice @file, $i, 1;
	    }
	}

	push @file, $dname . ":" . $password . "\n";

	open (DOMAINBAK, ">$config{'domains_cur'}");
	print DOMAINBAK @file;
	close (DOMAINBAK);
    }

    &qmail_control_check();

    return $err_msg;
}

#delete_domain($dname)
sub delete_domain()
{
    my ($dname);
    my ($out, $err_msg);
    my (@file, $i , @line);

    $dname = @_[0];
    $err_msg = "";

    $out = &ez_system12 ($config{'vdeldomain'}, $dname);

    if ($out =~ /error/i)
    {
	$err_msg = &text('msg_err_deldomain', $dname);
    }
    else
    {
	open (DOMAINBAK,"$config{'domains_cur'}");
	@file = <DOMAINBAK>;
	close (DOMAINBAK);

	for ($i = @file - 1; $i >= 0; $i--)
	{
	    @line = split (':', $file[$i]);
	    if ($line[0] eq $dname)
	    {
		splice @file, $i, 1;
	    }
	}

	open (DOMAINBAK, ">$config{'domains_cur'}");
	print DOMAINBAK @file;
	close (DOMAINBAK);
    }

    &qmail_control_check();

    return $err_msg;
}

#is_ipport_used($port)
sub is_ipport_used()
{
    my (@file, $i, $port, @line);

    $port = @_[0];
    $port = sprintf "%04x", $port;
    $port = uc $port;

    @file = split "\n", &ez_system12('cat', '/proc/net/tcp', '/proc/net/udp');

    for ($i = 0; $i < @file; $i++)
    {
	chomp($file[$i]);

	$file[$i] =~ s/^\s+//;
	if ($file[$i] !~ /^\d+/)
	{
	    next;
	}

	@line = split(/\s+/, $file[$i]);
	@line = split(":", $line[1]);
	if ($port eq $line[1])
	{
	    return 1;
	}
    }
    return 0;
}


#get_wbmail_port()
#return $prot
sub get_wbmail_port()
{
    my ($prot, @file, $i, $addr);

    $port = $config{'dft_wbmail_port'};

    open (WBMAILCONF, $config{'wbmailconf'});
    @file = <WBMAILCONF>;
    close (WBMAILCONF);

    for ($i = 0; $i < @file; $i++)
    {
	chomp($file[$i]);

	$file[$i] =~ s/#.*//;
	if ($file[$i] =~ /Listen\s+/)
	{
	    $addr = $file[$i];
	    $addr =~ s/^.*Listen\s+//i;
	    if ($addr !~ /:/)
	    {
		$port = $addr;
		last;
	    }
	}
    }

    return $port;
}

#save_wbmail_port($port)
sub save_wbmail_port()
{
    my ($port, @file, $i, $addr, $tmpstr);

    $port = $config{'dft_wbmail_port'};

    $port = @_[0] if (@_[0]);

    open (WBMAILCONF, $config{'wbmailconf'});
    @file = <WBMAILCONF>;
    close (WBMAILCONF);

    for ($i = 0; $i < @file; $i++)
    {
	$tmpstr = $file[$i];
	chomp($tmpstr);

	$tmpstr =~ s/#.*//;
	if ($tmpstr =~ /Listen\s+/)
	{
	    $addr = $tmpstr;
	    $addr =~ s/^.*Listen\s+//i;
	    if ($addr !~ /:/)
	    {
		$file[$i] = "Listen   $port"."\n";
		last;
	    }
	}
    }

    open (WBMAILCONF, "> $config{'wbmailconf'}");
    print WBMAILCONF @file;
    close (WBMAILCONF);
}

#get_wbmail_msgsize()
#return $msgsizeMB;
sub get_wbmail_msgsize()
{
    my ($msgsizeMB, @file, $i);

    $msgsizeMB = $config{'dft_wbmail_msgsizeMB'};

    open(PHPINI, $config{'phpini'});
    @file = <PHPINI>;
    close(PHPINI);

    for ($i = 0; $i < @file; $i++)
    {
	chomp($file[$i]);

	$file[$i] =~ s/;.*$//;
	$file[$i] =~ s/#.*$//;

	if ($file[$i] =~ /upload_max_filesize.*(\d+)/)
	{
	    $msgsizeMB = $1;
	    last;
	}
    }

    return $msgsizeMB;
}

#save_wbmail_msgsize($msgsizeMB)
sub save_wbmail_msgsize()
{
    my ($msgsizeMB, @file, $i, $tmpstr);

    $msgsizeMB = @_[0];

    open(PHPINI, $config{'phpini'});
    @file = <PHPINI>;
    close(PHPINI);

    for ($i = 0; $i < @file; $i++)
    {
	$tmpstr = $file[$i];

	chomp($tmpstr);

	$tmpstr =~ s/;.*$//;
	$tmpstr =~ s/#.*$//;

	if ($tmpstr =~ /upload_max_filesize.*(\d+)/)
	{
	    $file[$i] = "upload_max_filesize = $msgsizeMB"."M"."\n";
	    last;
	}
    }

    open (PHPINI, "> $config{'phpini'}");
    print PHPINI @file;
    close (PHPINI);

    return $msgsizeMB;
}


#mail_error(\@header_param, \@footer_param, $title, $message)
sub mail_error()
{
    my ($ptr_headp, $ptr_footp, $title, $msg);

    $ptr_headp = @_[0];
    $ptr_footp = @_[1];
    $title = @_[2];
    $msg = @_[3];

    &header(@$ptr_headp);

#    print "<hr>";

    print "<b>$title :&nbsp;&nbsp;</b>$msg";

#    print "<hr>";
    &footer(@$ptr_footp);
}

#qmail_control_check()
sub qmail_control_check()
{    
    &ez_system('rm', '-f', $config{'rcpthosts_f'}, $config{'morercpthosts_f'}, $config{'rcpthosts_lock_f'});
}

#qmail_dir_check()
#return mail config file and user data file is correct exist;
sub qmail_dir_check()
{
    my ($rt_correct, $mntroot, @vols, $path);
    my ($mailroot);
    my (@file, @line, $i);

    $mntroot = &get_mnt_root();

    @vols = &get_volumes();

    open(MDIRCONF, $config{'qmaildir'});
    @file = <MDIRCONF>;
    close(MDIRCONF);

    for ($i = 0; $i < @file; $i++)
    {
	chomp ($file[$i]);
	$file[$i] =~ s/#.*$//;

	@line = split ("=", $file[$i]);
	if ($line[0] eq 'MAILROOT')
	{
	    $mailroot = $line[1];
	    next;
	}
    }

    for ($i = 0; $i < @vols; $i++)
    {
	$path = $mntroot . $vols[$i];
	if ($mailroot =~ /$path/)
	{
	    if (-d $mailroot)
	    {
		return 1;
	    }
	}
    }
    
    return 0;
}


#qmail_dir_set($vol)
sub qmail_dir_set()
{
    my ($input_vol, @file, $i, $out, $mailroot);
    my ($queuedir, $domainsdir, $tempdir, $path);

    $input_vol = @_[0];

    $mntroot = &get_mnt_root();
    @vols = &get_volumes();

    $mailroot = $mntroot . $input_vol . '/'. $config{'mailroot'};

    for ($i = 0; $i < @vols; $i++)
    {
	$path = $mntroot . $vols[$i];
	
	if ($input_vol eq $vols[$i])
	{
	    if (! (-d $mailroot) )
	    {
		$out = &ez_system('mkdir', $mailroot);
		$out = &ez_system('chmod', '777', $mailroot);
	    }

	    $queuedir = $mailroot . 'queue';
	    $out = &ez_system('rm', '-Rf', $queuedir);
	    $out = &ez_system('tar', 'xvfz', $config{'dft_queue_pak'}, '-C', $mailroot);
	    $out = &ez_system('rm', '-f', $config{'flink_queue'});
	    $out = &ez_system('ln', '-s', $queuedir, $config{'flink_queue'});

	    $domainsdir = $mailroot . 'domains';
	    $out = &ez_system('rm', '-Rf', $domainsdir);
	    $out = &ez_system('mkdir', $domainsdir);
	    $out = &ez_system('chmod', '700', $domainsdir);
	    $out = &ez_system('chown', 'vpopmail:vchkpw', $domainsdir);
	    $out = &ez_system('rm', '-f', $config{'flink_domains'});
	    $out = &ez_system('ln', '-s', $domainsdir, $config{'flink_domains'});

	    $tempdir = $mailroot . 'temp';
	    $out = &ez_system('rm', '-Rf', $tempdir);
	    $out = &ez_system('mkdir', $tempdir);
	    $out = &ez_system('chmod', '777', $tempdir);
	    $out = &ez_system('chown', 'vpopmail:vchkpw', $tempdir);
	    $out = &ez_system('rm', '-f', $config{'flink_temp'});
	    $out = &ez_system('ln', '-s', $tempdir, $config{'flink_temp'});

	    open(MDIRCONF, ">$config{'qmaildir'}");
	    print MDIRCONF "MAILROOT=".$mailroot."\n";
	    close(MDIRCONF);

	    last;
	}
    }

    return "" if ($input_vol eq $vols[$i]);

    return &text('msg_err_path_not_in_usrvols', $input_vol);

}

#qmail_dir_get()
sub qmail_dir_get()
{
    my (@file, $i, @line, $mailroot);

    open(MDIRCONF, $config{'qmaildir'});
    @file = <MDIRCONF>;
    close(MDIRCONF);

    for ($i = 0; $i < @file; $i++)
    {
	chomp($file[$i]);
	$file[$i] =~ s/#.*$//;

	@line = split ("=", $file[$i]);
	if ($line[0] eq 'MAILROOT')
	{
	    $mailroot = $line[1];
	    last;
	}	
    }

    return $mailroot;
}

#mail_conf_check()
sub mail_conf_check()
{
    
}

#mail_conf_checkout()
sub mail_conf_checkout()
{
    my ($d, @data, $i, @field, $out);
    &foreign_require("mysql", "mysql-lib.pl");

    $d = &foreign_call("mysql", "execute_sql", 'vpopmail', 
		       "select pw_name, pw_domain, pw_shell, pw_clear_passwd from vpopmail order by pw_domain, pw_name");

    @data = @{$d->{'data'}};

    open (VPOPMAILBAK, "> $config{'vpopmail_bak'}");

    for ($i = 0; $i < @data; $i++)
    {
	@field = @{$data[$i]};

	#==============================================
	#== vpopmail.txt file format list as follow  ==
	#==   uname:dname:clearpassword:uquota  =======
	#==============================================

	printf VPOPMAILBAK "%s:%s:%s:%s\n", $field[0], $field[1], $field[2], $field[3];
    }

    close (VPOPMAILBAK);

    $out = &ez_system('cp', '-f' , $config{'domains_cur'}, $config{'domains_bak'});
    $out = &ez_system("date 1>$config{'back_conf_time'}");
}

#mail_conf_checkin()
sub mail_conf_checkin()
{
    my ($out, $i, @file, @line, $dir);

    &serv_act("popserv", "stop");
    &serv_act("smtpserv", "stop");
    &serv_act("mailserv", "stop");    
    &serv_act("webmailserv", "stop");
#    $out = &ez_system('/etc/init.d/mysqld', 'stop');


#=====================================================================
#===*make dir for all domains , in order to pretect lose domains dir==
#===*         delete all domains in domains.txt file                ==
#=====================================================================


    open (DOMAINBAK, $config{'domains_bak'});
    @file = <DOMAINBAK>;
    close (DOMAINBAK);

    for ($i = 0 ; $i < @file; $i++)
    {
       	chomp($file[$i]);

	@line = split(":", $file[$i]);

	if (-d $config{'domainsdir'})
	{
	    $dir = $config{'domainsdir'} . '/' . $line[0];
	    if (! (-d $dir))
	    {
		$out = &ez_system("mkdir",  $dir);
		$out = &ez_system("chmod", "vpopmail:vchkpw", $dir);
	    }
	    
	    $out = &ez_system($config{'vdeldomain'}, $line[0]);

	    if (-d $dir)
	    {
		$out = &ez_system("rm", "-Rf", $dir);
	    }
	}
    }

#=====================================================================
#===*          add all domains with domains.txt file                ==
#===*      add all users with address in vpopmail.txt file          ==
#=====================================================================

    open (DOMAINBAK, $config{'domains_bak'});
    @file = <DOMAINBAK>;
    close (DOMAINBAK);

    for ($i = 0 ; $i < @file; $i++)
    {
       	chomp($file[$i]);

	@line = split(":", $file[$i]);

	if (-d $config{'domainsdir'})
	{
	    $dir = $config{'domainsdir'} . '/' . $line[0];
	    
	    $out = &ez_system($config{'vadddomain'}, $line[0], $line[1]);
	}
    }

    &qmail_control_check();

    open (VPOPMAILBAK, $config{'vpopmail_bak'});
    @file = <VPOPMAILBAK>;
    close (VPOPMAILBAK);

    for ($i = 0 ; $i < @file; $i++)
    {
       	chomp($file[$i]);

	@line = split(":", $file[$i]);

	$out = &ez_system($config{'vadduser'}, $line[0]. "\@" . $line[1] , $line[3], "-q", $line[2]);
    }

}

sub get_mnt_root()
{
    my (@file, $i, @line);
    my $mntroot = "";

    open(STOR, $config{'voltab'});
    @file = <STOR>;
    close(STOR);

    for ($i = 0; $i < @file; $i++)
    {
	chomp($file[$i]);
	$file[$i] =~ s/#.*$//;
	
	@line = split ("=", $file[$i]);
	if ($line[0] eq 'volroot')
	{
	    $mntroot = $line[1];
	    $mntroot =~ s/\s+$//;
	    last;
	}
    }

    return $mntroot;
}


sub get_volumes()
{
    my (@vols, $i, @file, @line);

    open(STOR, $config{'voltab'});
    @file = <STOR>;
    close (STOR);

    my $n = 0;
    my $mntroot;

    for ($i = 0; $i < @file; $i++)
    {
	chomp ($file[$i]);
	$file[$i] =~ s/#.*$//;

	if ($file[$i] =~ /^\s*volroot=\s*(\S*).*$/)
	{
	    $mntroot = $1;
	    $mntroot =~ s/\s+//g;
	    next;
	}
	elsif ($file[$i] =~ /^\s*(\S+)\s+\S*\s+(\S*).*$/)
	{
	    @line = split (/\s+/, $file[$i]);

	    $pname = $line[0];
	    $mntstatus = $line[2];
	    next if ($mntstatus ne 'normal');
	    $path = "$mntroot$pname";
	    if (!(-d $path)) { next; }
	    push(@vols, $pname);
	}
    }

    @vols = sort @vols;
    return @vols;
}

#get_child_dir($path)
sub get_child_dir()
{
    my ($path, $out, @file, $i);

    $path = @_[0];

    @file = split "\n", &ez_system12('ls', $path);

    for ($i = @file - 1; $i >= 0; $i--)
    {
	chomp($file[$i]);

	$file[$i] =~ s/.*\/+//g;
	if(! -d ($path . "/" . $file[$i]))
	{
	    splice @file, $i, 1;
	}
    }

    return @file;
}

#get_child_file($path)
sub get_child_dir_files()
{
    my ($path, $out, @file, $i, @dir, @file);

    $path = @_[0];

    opendir(DIR, $path);
    @file = readdir(DIR);
    closedir(DIR);

    for ($i = 0; $i < @file; $i++)
    {
	chomp($file[$i]);

	$file[$i] =~ s/.*\/+//g;
	
	if (-d ($path . "/" . $file[$i]))
	{
	    $file[$i] = "[dir]:" . $file[$i];
	    next;
	}
	if (-f ($path . "/" . $file[$i]))
	{
	    $file[$i] = "[file]:" . $file[$i];
	}
    }

    return sort @file;
}

#mail_conf_loadout($type, $dirpath)
sub mail_conf_loadout()
{
    my ($out, $type, $mailroot);
    my ($dirpath);

    $type = @_[0];
    $dirpath = @_[1];
    $mailroot = qmail_dir_get();

    if ($type eq "userdata")
    {
	#======================================================
	#==        clean all tgz file and cpt file      =======
	#======================================================

	$out = &ez_system("cd $dirpath;  rm -f $config{'mailbakfname'} mailroot.tgz users.tgz vpopdb.tgz control.tgz;");

	#======================================================
	#== backup mailroot userdata and empty queue    =======
	#== add tgz file mailroot.tgz at mailroot dir   =======
	#======================================================

	#$out = &ez_system("cd $mailroot; rm -rf temp/*;");
	#$out = &ez_system($config{'emptyqueue'});
	$out = &ez_system("cd $mailroot; tar cvfz $dirpath/mailroot.tgz *;");


	#=======================================================
	#== backup server config file and dir        ===========
	#== such as /var/local/mysql/vpopmail        ===========
	#== /var/qmail/users the domains info db file ==========
	#== /var/qmail/control the server config     ===========
	#=======================================================

	#$out = &ez_system("cd $config{'usersdir'}; tar cvfz $dirpath/users.tgz .");
	#$out = &ez_system("cd $config{'vpopdbdir'}; tar cvfz $dirpath/vpopdb.tgz .");
	#$out = &ez_system("cd $config{'controldir'}; tar cvfz $dirpath/control.tgz .");


        #=======================================================
	#====  tar a file bak_loadout_ud.tar                ====
	#=======================================================

	$out = &ez_system("cd $dirpath; tar cvf $dirpath/$config{'mailbakfname'} mailroot.tgz; rm -f mailroot.tgz; ccrypt -e -K $config{'cptkey'} -S '' $config{'mailbakfname'};");
    }
    elsif ($type eq "nouserdata")
    {
	#======================================================
	#==        clean all tgz file and cpt file      =======
	#======================================================

	$out = &ez_system("cd $dirpath;  rm -f $config{'mailbakfname'} users.tgz vpopdb.tgz control.tgz;");


	#=======================================================
	#== backup server config file and dir        ===========
	#== such as /var/local/mysql/vpopmail        ===========
	#== /var/qmail/users the domains info db file ==========
	#== /var/qmail/control the server config     ===========
	#=======================================================

	$out = &ez_system("cd $config{'usersdir'}; tar cvfz $dirpath/users.tgz .");
	$out = &ez_system("cd $config{'vpopdbdir'}; tar cvfz $dirpath/vpopdb.tgz .");
	$out = &ez_system("cd $config{'controldir'}; tar cvfz $dirpath/control.tgz .");
	&bak_vpopmail_vuname();
	$out = &ez_system("cd $dirpath; cp -f $config{'vpopmail_bak'} ./vpopmail.txt");


        #=======================================================
	#====  tar a file bak_loadout_ud.tar                ====
	#=======================================================

	$out = &ez_system("cd $dirpath; tar cvf $dirpath/$config{'mailbakfname'} users.tgz vpopdb.tgz control.tgz vpopmail.txt; rm -f users.tgz vpopdb.tgz control.tgz vpopmail.txt; ccrypt -e -K $config{'cptkey'} -S '' $config{'mailbakfname'};");
    }
}

#mail_conf_loadin($type, $dirpath, $fname, $selvol)
#return msg
sub mail_conf_loadin()
{
    my ($out, $type, $mailroot, $selvol);
    my ($dirpath, $mntroot, @v, $k, %isvol);


    $type = @_[0];
    $dirpath = @_[1];
    $fname = @_[2];
    $selvol = @_[3];

    $mntroot = &get_mnt_root();
    @v = &get_volumes();

    if (@v < 1)
    {
	return "";
    }

    foreach $k (@v)
    {
	$isvol{$k} = "yes";
    }

    if ($isvol{$selvol} eq 'yes')
    {
	$mailroot = $mntroot . $selvol . '/' . $config{'mailroot'};
    }
    else
    {
	$mailroot = qmail_dir_get();
    }

    #======================================================
    #  dcrypt loadin file and check file format         ===
    #======================================================
	
    $out = &ez_system12("cd $dirpath; cp -f $fname $fname.tmp");

    $out = &ez_system12("cd $dirpath; ccrypt -d -K $config{'cptkey'} -S '' $fname;");

    if ($out)
    {
	$err_msg = $text{'err_msg_fileformat'};
	return $err_msg;
    }
	

    #=====================================================
    #     stop all mail server service                   =
    #=====================================================

    #&serv_act("popserv", "stop");
    &serv_act("smtpserv", "stop");
    &serv_act("webmailserv", "stop");
    #&serv_act("mailserv", "stop");


    #=====================================================
    #  recorver mailroot dir and extract mailroot.tgz    =
    #=====================================================
    
    $out = &ez_system("cd $dirpath; tar xvf $fname;");
    if (-f ($dirpath . '/' . 'vpopmail.txt'))
    {
	$type = 'nouserdata';
    }
    else
    {
	$type = 'userdata';
    }
    
    if ($type eq 'userdata')
    {

	#=====================================================
	#  recorver mailroot dir and extract mailroot.tgz    =
	#=====================================================

	$out = &ez_system("rm" , "-rf" , $mailroot);
	$out = &ez_system("mkdir", $mailroot);
	$out = &ez_system("chmod 777 $mailroot");
	$out = &ez_system("cd $dirpath; tar xvfz mailroot.tgz -C $mailroot");


	#======================================================
	#                stop mysql server                    =
        #              recover servers config                 =
        #         controls.tgz  users.tgz  vpopdb.tgz         =
	#                start mysql server                   =
	#======================================================

	#$out = &ez_system("/etc/init.d/mysqld stop");
	#$out = &ez_system("rm -rf $config{'vpopdbdir'}/*");
	#$out = &ez_system("cd $dirpath; tar xvfz vpopdb.tgz -C $config{'vpopdbdir'}");
	#$out = &ez_system("/etc/init.d/mysqld start");

	#$out = &ez_system("rm -rf $config{'usersdir'}/*");
	#$out = &ez_system("cd $dirpath; tar xvfz users.tgz -C $config{'usersdir'}");

	#$out = &ez_system("rm -rf $config{'controldir'}/*");
	#$out = &ez_system("cd $dirpath; tar xvfz control.tgz -C $config{'controldir'}");


	#=======================================================
	#  remove all backup midile create files               =
	#=======================================================
	
	$out = &ez_system("cd $dirpath; rm -f $fname control.tgz vpopdb.tgz users.tgz mailroot.tgz");
	$out = &ez_system("cd $dirpath; mv -f $fname.tmp $fname");
	$out = &ez_system("date 1>$config{'back_conf_time'}");

	#&serv_act("mailserv", "start");
	&serv_act("popserv", "start");
	&serv_act("smtpserv", "start");
	#&serv_act("webmailserv", "start");
    }
    elsif ($type eq 'nouserdata')
    {
	#=====================================================
	#    extract input data file and copy vpopmail.txt   =
	#=====================================================

	$out = &ez_system("cd $dirpath; mv -f vpopmail.txt $config{'vpopmail_bak'}");

	#======================================================
	#                stop mysql server                    =
        #              recover servers config                 =
        #         controls.tgz  users.tgz  vpopdb.tgz         =
	#                start mysql server                   =
	#======================================================

	$out = &ez_system("/etc/init.d/mysqld stop");
	$out = &ez_system("rm -rf $config{'vpopdbdir'}/*");
	$out = &ez_system("cd $dirpath; tar xvfz vpopdb.tgz -C $config{'vpopdbdir'}");
	$out = &ez_system("/etc/init.d/mysqld start");

	$out = &ez_system("rm -rf $config{'usersdir'}/*");
	$out = &ez_system("cd $dirpath; tar xvfz users.tgz -C $config{'usersdir'}");

	$out = &ez_system("rm -rf $config{'controldir'}/*");
	$out = &ez_system("cd $dirpath; tar xvfz control.tgz -C $config{'controldir'}");

	#=====================================================
	#  recorver mailroot dir and recreate mailroot dir   =
	#=====================================================

	&recreate_mailroot($mailroot);

	#=======================================================
	#  remove all backup midile create files               =
	#=======================================================
	
	$out = &ez_system("cd $dirpath; rm -f $fname control.tgz vpopdb.tgz users.tgz mailroot.tgz vpopmail.txt");
	$out = &ez_system("cd $dirpath; mv -f $fname.tmp $fname");
	$out = &ez_system("date 1>$config{'back_conf_time'}");

	&serv_act("mailserv", "start");
	&serv_act("popserv", "start");
	&serv_act("smtpserv", "start");
	&serv_act("webmailserv", "start");
    }

    return "";
}

#mail_conf_chgdir($vols)
sub mail_conf_chgdir()
{
    my ($vols, $mailroot, $mntroot, $newdir);
    my ($queuedir, $domainsdir, $tempdir, @v);

    $vols = @_[0];
    $mailroot = qmail_dir_get();
    $mntroot = &get_mnt_root();
    @v = &get_volumes();

    if (! (-d $mailroot))
    {
	recreate_mailroot($mailroot);
    }
    $out = &ez_system("rm -f /sysvol/.mail");
    $newdir = $mntroot . $vols . "/" . $config{"mailroot"};
    $out = &ez_system("ln -s $newdir /sysvol/.mail");

    if ($mailroot =~ /^$mntroot$vols/)
    {
	return ;
    }
    if (@v < 1)
    {
	return ;
    }

    $newdir = $mntroot . $vols . "/" . $config{"mailroot"};
    #$queuedir = $newdir . 'queue';
    #$domainsdir = $newdir . 'domains';
    #$tempdir = $newdir . 'temp';

    &serv_act("popserv", "stop");
    &serv_act("smtpserv", "stop");
    #&serv_act("webmailserv", "stop");
    #&serv_act("mailserv", "stop");
    
    #============================================================
    #         remove $vols .mailroot directory                  =
    #       cpoy current mailroot dir to input vols mailroot    =
    #         modify file link to mailroot directories          =
    #============================================================

    $out = &ez_system("rm -rf $newdir");
    $out = &ez_system("mv -f $mailroot $newdir");
	
    $out = &ez_system("rm -f /sysvol/.mail");
    $out = &ez_system("ln -s $newdir /sysvol/.mail");
    #$out = &ez_system('rm', '-f', $config{'flink_queue'});
    #$out = &ez_system('ln', '-s', $queuedir, $config{'flink_queue'});
    #$out = &ez_system('rm', '-f', $config{'flink_domains'});
    #$out = &ez_system('ln', '-s', $domainsdir, $config{'flink_domains'});
    #$out = &ez_system('rm', '-f', $config{'flink_temp'});
    #$out = &ez_system('ln', '-s', $tempdir, $config{'flink_temp'});    

    open(MDIRCONF, ">$config{'qmaildir'}");
    print MDIRCONF "MAILROOT=".$newdir."\n";
    close(MDIRCONF);

    #&serv_act("mailserv", "start");
    &serv_act("popserv", "start");
    &serv_act("smtpserv", "start");
    #&serv_act("webmailserv", "start");
}

#save_badmailfrom(\@badmailfrom)
sub save_badmailfrom()
{
    my ($ptr, $i);

    $ptr = @_[0];

    open (BADMAILFROM, "> $config{'badmailfrom_f'}");
    for ($i = 0; $i < @$ptr; $i++)
    {
	print BADMAILFROM $ptr->[$i], "\n";
    }
    close (BADMAILFROM);
}

#read_badmailfrom(\@badmailfrom)
sub read_badmailfrom()
{
    my (@line, $i, @file, @domains, @addr);

    open (BADMAILFROM, $config{'badmailfrom_f'});
    @file = <BADMAILFROM>;
    close (BADMAILFROM);

    for ($i = 0; $i < @file; $i++)
    {
	chomp($file[$i]);
	if ($file[$i] =~ /^\@/)
	{
	    push @domains, $file[$i];
	}
	elsif ($file[$i])
	{
	    push @addr, $file[$i];
	}
    }

    @domains = sort @domains;
    @addr = sort @addr;

    splice @addr, 0, 0, @domains;
    return @addr;
}


#recreate_mailroot($mailroot)
sub recreate_mailroot()
{
    my ($mailroot);
    my ($queuedir, $domainsdir, $tempdir);
    my ($i, @file );

    $mailroot = @_[0];

    unless ($mailroot)
    {
	$mailroot = qmail_dir_get();
    }

    #=================================================
    #    remove current mailroot and                 =
    #    create current mailroot and                 =
    #    chmod 777 to new mailroot dir               =
    #=================================================

    $out = &ez_system("rm" , "-Rf" , $mailroot);
    $out = &ez_system("mkdir", $mailroot);
    $out = &ez_system("chmod 777 $mailroot");


    #=================================================
    #       recreate .mailroot/[queue|temp] dir      =
    #=================================================

    #$queuedir = $mailroot . 'queue';
    #$out = &ez_system('tar', 'xvfz', $config{'dft_queue_pak'}, '-C', $mailroot);

    $tempdir = $mailroot . 'temp';
    $out = &ez_system('mkdir', $tempdir);
    $out = &ez_system('chmod', '777', $tempdir);
    $out = &ez_system('chown', 'vpopmail:vchkpw', $tempdir);


    #=================================================
    #       recreate .mailroot/domains    dir        =
    #=================================================


    #$domainsdir = $mailroot . 'domains';
    #$out = &ez_system('rm', '-Rf', $domainsdir);
    #$out = &ez_system('mkdir', $domainsdir);
    #$out = &ez_system('chmod', '700', $domainsdir);
    #$out = &ez_system('chown', 'vpopmail:vchkpw', $domainsdir);

    #=================================================
    #    add all domains with vdomains file          =
    # add all users with address in vpopmail.txt file=
    #=================================================

    #open (VDOMAIN, $config{'virtualdomains_f'});
    #@file = <VDOMAIN>;
    #close (VDOMAIN);

#    for ($i = 0; $i < @file; $i++)
#    {
#	chomp($file[$i]);

#	@line = split (/:/, $file[$i]);
#	if($line[0])
#	{
#	    $out = &ez_system("cd $domainsdir; mkdir \'$line[0]\'; chown vpopmail:vchkpw \'$line[0]\'");
#	    open (QMAILDFT, "> $domainsdir/$line[0]/.qmail-default");
#	    print QMAILDFT "| /home/vpopmail/bin/vdelivermail \'\' bounce-no-mailbox\n";
#	    close(QMAILDFT);
#	    $out = &ez_system("chown", "vpopmail:vchkpw",  "$domainsdir/$line[0]/.qmail-default");
#        }
#    }

#   &qmail_control_check();

#    open (VPOPMAILBAK, $config{'vpopmail_bak'});
#    @file = <VPOPMAILBAK>;
#    close (VPOPMAILBAK);

#    for ($i = 0 ; $i < @file; $i++)
#    {
#       	chomp($file[$i]);
#
#	@line = split(":", $file[$i]);

#	if ($line[0] && $line[1])
#	{
#	    if (-d ($domainsdir . "/" . $line[1]))
#	    {
#		$out = &ez_system("cd $domainsdir; cd '$line[1]'; cp -Rf $config{'vuserdir'} ./$line[0]; chown -Rf vpopmail:vchkpw '$line[0]';");
#	    }
#	}
#    }
}

#bak_vpopmail_vuname()
sub bak_vpopmail_vuname()
{
    my ($d, @data, $i, @field, $out);
    &foreign_require("mysql", "mysql-lib.pl");

    $d = &foreign_call("mysql", "execute_sql", 'vpopmail', 
		       "select pw_name, pw_domain from vpopmail");

    @data = @{$d->{'data'}};

    open (VPOPMAILBAK, "> $config{'vpopmail_bak'}");

    for ($i = 0; $i < @data; $i++)
    {
	@field = @{$data[$i]};

	#==============================================
	#== vpopmail.txt file format list as follow  ==
	#==   uname:dname                       =======
	#==============================================

	printf VPOPMAILBAK "%s:%s\n", $field[0], $field[1];
    }

    close (VPOPMAILBAK);
}

1;
